<?php
// +----------------------------------------------------------------------
// | BhAdmin [ BhAdmin匠心打造，我们相信，每个伟大的软件都有一个伟大的故事 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2023 https://www.bhadmin.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed BhAdmin并不是自由软件，未经许可不能去掉BhAdmin相关版权
// +----------------------------------------------------------------------
// | Author: BAIHU  <admin@bhadmin.cn>
// +----------------------------------------------------------------------
namespace app\admin\logic;

use support\Exception\ApiException;
use support\Service\ConfigDataService;
use support\Service\ConfigService;

class ConfigDataLogic extends BaseLogic
{
    public function __construct()
    {
        self::$service = new ConfigDataService();
    }

    /**
     * 分页列表
     * @return array
     */
    public static function getListPage()
    {
        $param = request()->all();
        if (!isset($param['configId'])) {
            return message([]);
        }
        $where = [];
        $where[] = ["mark", '=', 1];
        $where[] = ["config_id", '=', (int)$param['configId']];
        $list = self::$service::getListPage($where, ['*'], ['sort' => 'asc'], [], $param['limit'] ?? 10);
        return message($list);
    }

    public static function editInfo()
    {

        $data = request()->post();
        $id = $data['id'] ?? 0;
        if (!isset($data['config_id']) || empty($data['config_id'])) {
            throw new ApiException('请选择配置分类');
        }
        if (!isset($data['title']) || empty($data['title'])) {
            throw new ApiException('请输入配置项标题');
        }
        if (!isset($data['type']) || empty($data['type'])) {
            throw new ApiException('请选择配置类型');
        }
        if (!isset($data['code']) || empty($data['code'])) {
            throw new ApiException('请输入配置项编码');
        }
        if (!isset($data['sort']) || empty($data['sort'])) {
            throw new ApiException('请输入排序');
        }
        $save['title'] = trim($data['title']);
        $save['sort'] = $data['sort'];
        $save['config_id'] = $data['config_id'];
        $save['type'] = $data['type'];
        $save['code'] = $data['code'] ?? '';
        $save['status'] = $data['status'] ?? 1;
        $save['value'] = $data['value'] ?? '';
        $save['options'] = $data['options'] ?? '';
        $save['note'] = $data['note'] ?? '';
        unset($data['id']);
        if ($id == 0) {
            $count = self::$service::getUserCountByWhere([["code", '=', $save['code']], ["mark", "=", 1]]);
            if ($count > 0) {
                throw new ApiException('系统中已存在相同的配置编码');
            }
            self::$service::add($save);
        } else {
            $count = self::$service::getUserCountByWhere([["code", '=', $save['code']], ["id", "<>", $id], ["mark", "=", 1]]);
            if ($count > 0) {
                throw new ApiException('系统中已存在相同的用户名');
            }
            self::$service::save($save, $id);
        }
        return message();

    }

    /**
     * 获取指定项目
     * @return array
     */
    public static function getList()
    {
        $ids = request()->post('ids', '1,2,3,4');
        $ids = explode(",", $ids);
        if (!$ids) {
            return message();
        }
        $configList = ConfigService::getAllList([['id', 'in', $ids], ['mark', '=', 1]]);
        if (!$configList) {
            return message();
        }
        $where[] = ["mark", '=', 1];
        $where[] = ["config_id", 'in', $ids];
        $list = self::$service::getList($where, ['*'], ['sort' => 'asc']);
        $dataList = [];
        if ($list) {
            foreach ($list as $i => $t) {
                $dataList[$t['config_id']][] = $t;
            }
        }

        $dataRes = [];
        foreach ($configList as $k => $v) {
            $configData = [];
            if (isset($dataList[$v['id']])) {
                foreach ($dataList[$v['id']] as &$val) {
                    if ($val['type'] == "array" || $val['type'] == "radio" || $val['type'] == "checkbox" || $val['type'] == "select") {
                        $data = preg_split('/[\r\n]+/s', $val['options']);
                        if ($data) {
                            $arr = [];
                            foreach ($data as $vt) {
                                $value = preg_split('/[:：]+/s', $vt);
                                $arr[$value[0]] = $value[1];
                            }
                            $val['param'] = $arr;
                        }
                        // 复选框
                        if ($val['type'] == "checkbox") {
                            $val['value'] = explode(",", $val['value']);
                        }
                    }
                    // 单图
                    if ($val['type'] == "image" && !empty($val['value'])) {

                    }

                    // 多图
                    if ($val['type'] == "images") {
                        $urlList = explode(",", $val['value']);
                        $itemList = [];
                        foreach ($urlList as $vt) {
                            if (empty($vt)) {
                                continue;
                            }
                            $itemList[] = $vt;
                        }
                        $val['value'] = $itemList;
                    }
                }
                $configData = $dataList[$v['id']];
            }
            $item = [];
            $item['config_id'] = $v['id'];
            $item['config_name'] = $v['name'];
            $item['item_list'] = $configData;
            $dataRes[$k] = $item;
        }
        return message($dataRes);
    }


    /**
     * 编辑配置
     * @return array
     */
    public static function edit()
    {
        $data = request()->post();
        if (!$data) {
            throw  new ApiException('参数不能为空');
        }
        foreach ($data as $key => $item) {
            $result = self::$service::getInfoByWhere([['code', '=', $key]]);
            if (!$result) continue;
            if (is_array($item)) {
                $item = !empty($item) ? implode(",", $item) : "";
            }
            $save = [];
            $save['value'] = !empty($item) ? $item : "";
            self::$service::save($save, $result['id']);
        }
        return message();
    }
}
